import { defineStore } from "pinia";
import api from "@/utils/api";
import {
  ImageStoreState,
  ProcessedImageItem,
} from "@/types/imageAndFile";
import request from "@/utils/request";
import { AxiosRequestHeaders } from "axios";

export const useImageStore = defineStore("imageStore", {
  state: (): ImageStoreState => ({
    images: [],
    cases: [],
    processedImages: [],
  }),
  actions: {
    /**
     * 上传图片获取AI分析结果
     * @param leftImages Array
     * @param rightImages Array
     * @returns Promise<ProcessdImageItem[]> 处理后的图片数组
     */
    async guestAnalyze(leftImages: File[], rightImages: File[]) {
      try {
        const formData = new FormData();
        if (!Array.isArray(leftImages) || !Array.isArray(rightImages)) {
          throw new Error("左右眼必须是数组类型");
        }
        leftImages.forEach((image) => {
          if (image instanceof File) {
            formData.append("leftImage", image);
          }
        });
        rightImages.forEach((image) => {
          if (image instanceof File) {
            formData.append("rightImage", image);
          }
        });
        let result: any = await request({
          method: "post",
          url: api.guestAnalyze,
          data: formData,
          headers: {
            "Content-Type": "multipart/form-data",
          } as AxiosRequestHeaders,
        });
        if (!result) {
          return;
        }
        if (result.code === 1) {
          this.processedImages = result.data.map(
            (item: ProcessedImageItem) => ({
              leftImages: item.leftImage || "",
              rightImages: item.rightImage || "",
              leftDiseaseResult: Array.isArray(item.leftDiseaseResult)
                ? item.leftDiseaseResult
                : [],
              rightDiseaseResult: Array.isArray(item.rightDiseaseResult)
                ? item.rightDiseaseResult
                : [],
              leftConfidence: Array.isArray(item.leftConfidence)
                ? item.leftConfidence
                : [],
              rightConfidence: Array.isArray(item.rightConfidence)
                ? item.rightConfidence
                : [],
              processedImgPaths: Array.isArray(item.processedImgPaths)
                ? item.processedImgPaths
                : [],
            })
          );
          //统计病例
          const diseaseCounts: Record<string, number> = {};
          this.processedImages.forEach((image) => {
            image.leftDiseaseResult.forEach((disease) => {
              if (disease) {
                diseaseCounts[disease] = (diseaseCounts[disease] || 0) + 1;
              }
            });
            image.rightDiseaseResult.forEach((disease) => {
              if (disease) {
                diseaseCounts[disease] = (diseaseCounts[disease] || 0) + 1;
              }
            });
          });
          //格式化
          this.cases = Object.entries(diseaseCounts).map(
            ([disease, count]) => ({
              disease,
              count,
            })
          );
          return result;
        }
      } catch (error) {
        throw error;
      }
    },
    clearAllData(): void {
      this.images = [];
      this.cases = [];
      this.processedImages = [];
    },
  },
});
